package org.scilab.forge.jlatexmath.web.controller;

import org.apache.commons.lang3.StringUtils;
import org.scilab.forge.jlatexmath.util.CoderUtil;
import org.scilab.forge.jlatexmath.util.ConvertUtil;
import org.scilab.forge.jlatexmath.web.model.RequestModel;
import org.scilab.forge.jlatexmath.web.model.ResponseModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * Created by Administrator on 2017-3-4.
 */
@RestController
@RequestMapping("/converter")
public class ImageConverterController {
    private static Logger logger = LoggerFactory.getLogger(ImageConverterController.class);

    @RequestMapping(value = "/png", method = RequestMethod.POST)
    public ResponseModel png(@RequestBody RequestModel model) {
        ResponseModel response = new ResponseModel();
        try {
            if (StringUtils.isBlank(model.getData())) {
                response.setSuc(false);
                response.setMessage("输入数据不能为空");
            } else {
                byte[] bytes = CoderUtil.decodeBase64(model.getData());
                String latext = new String(bytes, StandardCharsets.UTF_8);

                byte[] pngBytes = ConvertUtil.toPngByte(latext);

                String outData = CoderUtil.encodeBase64(pngBytes);
                response.setData(outData);
                response.setSuc(true);
            }
        } catch (Exception e) {
            response.setSuc(false);
            response.setMessage(e.getMessage());

            e.printStackTrace();
            logger.error("ImageConverterController.png=>" + e.getMessage());
        }

        return response;
    }
}
